<template>
  <div>
    <Card :bordered="true" dis-hover>
      <div slot="title">
        <Dropdown>
          <Button type="primary" ghost>
            添加成本中心
            <Icon type="ios-arrow-down"></Icon>
          </Button>
          <DropdownMenu slot="list">
            <DropdownItem @click.native="handleOpenCreateHeader"
              >添加顶级成本中心</DropdownItem
            >
            <DropdownItem
              :disabled="currentNode.id==='root'"
              @click.native="handleOpenCreateSider"
              >添加子成本中心
            </DropdownItem>
          </DropdownMenu>
        </Dropdown>
        <Button
          type="primary"
          ghost
          class="ivu-ml"
          v-show="!toggleExpand"
          @click="handleToggleExpandAll(true)"
        >
          <Icon type="md-list" />
          全部展开
        </Button>
        <Button
          type="primary"
          ghost
          class="ivu-ml"
          v-show="toggleExpand"
          @click="handleToggleExpandAll(false)"
        >
          <Icon type="md-list" />
          全部收起
        </Button>
        <Button
          type="error"
          ghost
          class="ivu-ml"
          v-show="selectedData.length"
          @click="handleDeleteMultiple"
        >
          <Icon type="md-trash" />
          批量删除
        </Button>
      </div>
      <div>
        <div class="ivu-p-8">
          <Input
            v-if="menuList.length || query !== ''"
            v-model="query"
            search
            placeholder="输入节点名称搜索"
            @on-change="handleSearch"
          />
        </div>
        <Tree :style="menuListStyle"
          :data="menuList"
          show-checkbox
          check-strictly
          @on-select-change="handleSelectNode"
          @on-check-change="handleCheckNode"
          @on-contextmenu="handleContextMenu"
        >
          <template slot="contextMenu">
              <DropdownItem @click.native="handleContextMenuEdit" v-if="currentNode && this.currentNode.nodeType=='center'"
              >编辑</DropdownItem
              >
            <DropdownItem @click.native="handleContextMenuCenterNew" v-if="currentNode && this.currentNode.nodeType=='center'"
              >添加子成本中心</DropdownItem
            >
            <DropdownItem
              divided
              @click.native="handleContextMenuDelete"
              style="color: #ed4014"
              >删除
            </DropdownItem>
          </template>
        </Tree>
      </div>
    </Card>
      <addModal
          v-bind="addPanel"
          :modelType="modelType"
          :columns="formColumns"
          :rules="rules"
          :zIndex="zIndex"
          @submit="handleAddSubmit"
      ></addModal>
      <editModal
          v-bind="editPanel"
          :modelType="modelType"
          :columns="formColumns"
          :rules="rules"
          :zIndex="zIndex"
          @submit="handleEditSubmit"
      ></editModal>
  </div>
</template>

<script>
    import { cloneDeep } from 'lodash';
    import addModal from '@/pages/components/newAddModal.vue';
    import editModal from '@/pages/components/editModal.vue';
    export default {
        components: { addModal,editModal },
        props: {
            classObject: {
                default: () => {
                    return null;
                }
            },
            className: {
                default: () => {
                    return '';
                }
            },
            type: {
                default: () => {
                    return '';
                }
            },
            modelType: {
                default: () => {
                    return '';
                }
            },
            data: {
                default: () => {
                    return [];
                }
            },
            addPanel: {
                default: () => {
                    return {
                        width: 1024,
                        zIndex: 100,
                        titleStyle: {},
                        drawer: {
                            show: false
                        },
                        cols: 2
                    }
                }
            },
            editPanel: {
                default: () => {
                    return {
                        width: 1024,
                        zIndex: 100,
                        titleStyle: {},
                        drawer: {
                            show: false
                        },
                        cols: 2,
                        data: {}
                    }
                }
            }
        },
        data () {
            return {
                rules: {
                    code: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    name: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ]
                },
                currentNode: {
                    id: 'root',
                    title: 'root'
                },
                menuList: [],
                sourceMenuList: [],
                zIndex: 1000,
                selectedData: [],
                toggleExpand: true,
                query: '',
                loading: false,
                nodeType:"center",
            };
        },
        computed: {
            lang () {
                return {
                    'en-US': {
                        confirmDelete: 'confirm delete',
                        cancel: 'cancel'
                    },
                    'zh-CN': {
                        confirmDelete: '删除确认',
                        cancel: '取消'
                    }
                }[this.G_Locale];
            },
            menuListStyle () {
                return {
                    height: document.body.clientHeight - 64-48-61-32-48-20 + 'px',
                    overflow: 'auto'
                }
            },
            columns () {
                return [
                    {
                        key: 'code',
                        title: {
                            'zh-CN': '编码',
                            'en-US': 'code'
                        }[this.G_Locale],
                        minWidth: 100,
                        align: 'center',
                        show: true
                    },
                    {
                        key: 'name',
                        title: {
                            'zh-CN': '名称',
                            'en-US': 'name'
                        }[this.G_Locale],
                        minWidth: 100,
                        align: 'center',
                        show: true
                    },
                    {
                        key: 'brevity',
                        title: {
                            'zh-CN': '简码',
                            'en-US': 'brevity'
                        }[this.G_Locale],
                        minWidth: 70,
                        align: 'center',
                        show: true
                    },
                    {
                        key: 'remark',
                        title: {
                            'zh-CN': '备注',
                            'en-US': 'remark'
                        }[this.G_Locale],
                        minWidth: 100,
                        align: 'center',
                        show: true
                    }
                ];
            },
            // form中列字段
            formColumns () {
                return [
                    {
                        key: 'code',
                        title: {
                            'zh-CN': '编码',
                            'en-US': 'code'
                        }[this.G_Locale],
                        minWidth: 100,
                        align: 'center',
                        config: { type: 'text' }
                    },
                    {
                        key: 'name',
                        title: {
                            'zh-CN': '名称',
                            'en-US': 'name'
                        }[this.G_Locale],
                        minWidth: 100,
                        align: 'center',
                        config: { type: 'text' }
                    },
                    {
                        key: 'brevity',
                        title: {
                            'zh-CN': '简码',
                            'en-US': 'brevity'
                        }[this.G_Locale],
                        minWidth: 70,
                        align: 'center',
                        config: { type: 'text' }
                    },
                    {
                        key: 'remark',
                        title: {
                            'zh-CN': '备注',
                            'en-US': 'remark'
                        }[this.G_Locale],
                        minWidth: 100,
                        align: 'center',
                        config: { type: 'textarea' }
                    }
                ];
            }
        },
        watch: {
            data: {
                handler () {
                    this.menuList = this.getChildren('root')
                    this.sourceMenuList = this.menuList
                },
                deep: true
            }
        },
        mounted () {
            this.menuList = this.getChildren('root')
            this.sourceMenuList = this.menuList
        },
        methods: {
            getChildren (parentId) {
                let children = [];
                let list = this.data.filter(item => item.parentId === parentId && item.values.nodeType =='center');
                list.map(item => {
                    children.push({
                        title: item.values.sf_name ? `${item.values.sf_name}` : item.values.name,
                        id: item.id,
                        parentId: item.parentId,
                        contextmenu: true,
                        expand: true,
                        data: item,
                        pointer: item.pointer,
                        children: this.getChildren(item.id)
                    })
                });
                return children;
            },
            // 打开新增成本中心弹窗
            handleContextMenuCenterNew () {
                this.nodeType = "center";
                this.$set(this.addPanel.drawer, 'show', true);
            },
            // 新增成本中心保存
            handleAddSubmit (data) {
                let newData = {
                    id: this.tools.uuid(8),
                    name: data.values['name'],
                    title: data.values['name'],
                    values: {
                        nodeType:this.nodeType,
                        ...data.values
                    },
                    pointer: {},
                    parentId: this.currentNode.id
                };
                this.$emit('handleAddSubmit', newData)
            },
            // 打开编辑部门弹窗
            handleContextMenuEdit () {
                this.loading = true;
                if (!!this.classObject.record && !!this.classObject.record.hier && !!this.classObject.record.hier[0]) {
                    let index = this.classObject.record.hier[0].basic.findIndex(d => d.id === this.currentNode.id)
                    if (index !== -1) {
                        this.$set(this.editPanel, 'data', this.classObject.record.hier[0].basic[index]);
                        this.$set(this.editPanel.drawer, 'show', true);
                    }
                    this.loading = false;
                } else {
                    this.loading = false;
                }
            },

            // 编辑成本科目
            handleEditSubmit (data) {
                let newData = {
                    id: data.id,
                    name: data.name,
                    title: data.name,
                    values: {
                        ...data.values
                    },
                    pointer: {},
                    parentId: !!data.parentId ? data.parentId : 'root'
                };
                this.$emit('handleEditSubmit', newData)
            },
            // 打开查看成本中心弹窗
            handleContextMenuRead () {
                this.loading = true;
                if (!!this.classObject.record && !!this.classObject.record.hier && !!this.classObject.record.hier[0]) {
                    let index = this.classObject.record.hier[0].basic.findIndex(d => d.id === this.currentNode.id)
                    if (index !== -1) {
                        this.$set(this.readPanel, 'data', this.classObject.record.hier[0].basic[index].values);
                        this.$set(this.readPanel.drawer, 'show', true);
                    }
                    this.loading = false;
                } else {
                    this.loading = false;
                }
            },
            // 清空所有已选项
            handleClearSelect () {
                this.selectedData = [];
            },
            // 展开所有树
            handleToggleExpandAll (status) {
                this.toggleExpand = status;
                this.menuList = this.handleToggleExpandNode(this.menuList, status, []);
            },
            /**
             * @description 递归状态
             * @param {Array} menuList 原数据
             * @param {Boolean} isExpand 是否展开
             * @param {Array} lastList 递归数据
             * */
            handleToggleExpandNode (menuList, isExpand, lastList) {
                menuList.forEach(menu => {
                    let newMenu = {};
                    for (let i in menu) {
                        if (i !== 'children') newMenu[i] = cloneDeep(menu[i]);
                    }
                    newMenu.expand = isExpand;
                    newMenu.contextmenu = true;
                    if (menu.children && menu.children.length) newMenu.children = [];
                    lastList.push(newMenu);
                    menu.children && this.handleToggleExpandNode(menu.children, isExpand, newMenu.children);
                });
                return lastList;
            },
            // 左击选中
            handleSelectNode (currentArr, item) {
                this.currentNode = { ...item,nodeType:item.data && item.data.values && item.data.values.nodeType?item.data.values.nodeType:"center" };
                this.$emit('handleSelectNode', this.currentNode)
            },
            handleCheckNode (items) {
                this.selectedData = items;
            },
            // 右击
            handleContextMenu (item) {
                this.currentNode = { ...item,nodeType:item.data && item.data.values && item.data.values.nodeType?item.data.values.nodeType:"center" };
                this.$emit('handleSelectNode', this.currentNode)
            },
            handleSearch () {
                const query = this.query;
                this.selectedData = [];
                this.contextMenuInfo = null;
                if (query) {
                    this.menuList = this.handleQueryNode(this.sourceMenuList, query, []);
                } else {
                    this.handleInitMenuList();
                }
            },
            handleInitMenuList () {
                this.menuList = cloneDeep(this.sourceMenuList);
                this.handleToggleExpandAll(true);
            },
            handleQueryNode (menuList, query, queryList) {
                menuList.forEach(menu => {
                    let newMenu = {};
                    for (let i in menu) {
                        if (i !== 'children') newMenu[i] = cloneDeep(menu[i]);
                    }
                    if (newMenu.title.indexOf(query) > -1) queryList.push(newMenu);
                    if (menu.children && menu.children.length) newMenu.children = [];
                    menu.children && this.handleQueryNode(menu.children, query, queryList);
                });
                return queryList;
            },
            handleOpenCreateHeader () {
                this.$set(this.addPanel.drawer, 'show', true);
                this.$emit('handleSelectNode', {
                    id: 'root',
                    title: 'root'
                })
            },
            handleOpenCreateSider () {
                this.$set(this.addPanel.drawer, 'show', true);
            },
            // 删除成本中心
            handleContextMenuDelete () {
                if (this.submitting) return;
                this.$Modal.confirm({
                    title: this.lang['confirmDelete'],
                    cancelText: this.lang['cancel'],
                    content: `您确认要删除成本中心<strong>${this.currentNode.title}</strong>吗？`,
                    loading: this.loading,
                    onOk: () => {
                        this.deleteMenu();
                    }
                });
            },
            // 确认删除成本中心
            deleteMenu () {
                let menu = this.data.find(item => item.parentId === this.currentNode.id);
                if (!!menu) {
                    this.$Modal.remove();
                    this.$Message.warning('要删除的成本中心已经被使用不能删除！');
                    return;
                }
                let names = [];
                if (!!this.currentNode.data && !!this.currentNode.data.name) {
                    names = [this.currentNode.data.name]
                }
                let pointer = { className: this.className, type: this.type }
                // 解绑hier中某项的接口
                this.loading = true;
                this.classObject
                    .runRemoveRegister(pointer, names)
                    .then((flag) => {
                        if (flag) {
                            this.loading = false;
                            names.forEach((name) => {
                                let index = this.data.findIndex(
                                    (d) => d.name === name
                                );
                                if (index !== -1) {
                                    this.classObject.record.hier[0].basic.splice(index, 1);
                                }
                            });
                            this.currentNode = {
                                id: 'root',
                                title: '未选中'
                            }
                            this.$emit('handleSelectNode', this.currentNode)
                        } else {
                            this.loading = false;
                        }
                });
            },
            // 批量删除成本中心
            handleDeleteMultiple () {
                if (this.submitting) return;
                const ids = this.selectedData.map(item => item.data.name);
                const titles = this.selectedData.map(item => item.title);
                this.$Modal.confirm({
                    title: this.lang['confirmDelete'],
                    cancelText: this.lang['cancel'],
                    content: `您确认要删除成本中心<strong>${titles}</strong>吗？`,
                    loading: this.loading,
                    onOk: () => {
                        this.deleteMenuMultiple(ids);
                    }
                });
            },
            // 确认批量删除成本中心
            deleteMenuMultiple (names) {
                for (let i = 0; i < names.length; i++) {
                    let menu = this.data.find(item => item.parentId === names[i]);
                    if (!!menu) {
                        this.$Modal.remove();
                        this.$Message.warning('要删除的成本中心' + menu.title + '已经被使用不能删除！');
                        return;
                    }
                }
                let pointer = { className: this.className, type: this.type }
                // 解绑hier中某项的接口
                this.loading = true;
                this.classObject
                    .runRemoveRegister(pointer, names)
                    .then((flag) => {
                        if (flag) {
                            this.loading = false;
                            names.forEach((name) => {
                                let index = this.data.findIndex(
                                    (d) => d.name === name
                                );
                                if (index !== -1) {
                                    this.classObject.record.hier[0].basic.splice(index, 1);
                                }
                            });
                            this.currentNode = {
                                id: 'root',
                                title: '未选中'
                            }
                            this.$emit('handleSelectNode', this.currentNode)
                        } else {
                            this.loading = false;
                        }
                });
            }
        }
    };
</script>
<style scoped lang="scss">
.deptTree-page{
    width: 800px;
    //margin-top: 10px;
}
</style>
